/**
 * 请求取消控制器
 */

// 存储请求标识和控制器
const pendingMap = new Map();

/**
 * 生成每个请求唯一的键
 * @param {*} config 
 * @returns string
 */
function getPendingKey(config) {
    let { url, method, params, data } = config;
    let pendingData = data;
    if (pendingData) {
        if (typeof pendingData === 'string') {
            pendingData = JSON.parse(pendingData);
        } else {
            pendingData = {...pendingData};
        }
        delete pendingData.startDate;
        delete pendingData.endDate;
        delete pendingData.cities;
        delete pendingData.provinces;
    }
    return [url, method, JSON.stringify(params), JSON.stringify(pendingData)].join('&');
}

/**
 * 储存每个请求的标识和取消控制器
 * @param {*} config 
 */
function addPending(config) {
    const pendingKey = getPendingKey(config);
    
    // 如果存在相同请求，则取消前一个请求
    if (pendingMap.has(pendingKey)) {
        const controller = pendingMap.get(pendingKey);
        controller.abort();
        pendingMap.delete(pendingKey);
    }
    
    // 创建新的 AbortController
    const controller = new AbortController();   
    config.signal = controller.signal;
    pendingMap.set(pendingKey, controller);
}

/**
 * 删除请求标识
 * @param {*} config 
 */
function removePending(config) {
    const pendingKey = getPendingKey(config);
    pendingMap.delete(pendingKey);
}

export {
    addPending,
    removePending
} 